package com.youuvs.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.youuvs.ZuulApp;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {
    //创建当前类的日志器,其效果和lombok提供的@slf4j一致
    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);
    //设置执行顺序优先级
    private static final int order = 1;

    //filterType:"pre"前置
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //执行顺序(优先级)
    @Override
    public int filterOrder() {
        return order;
    }

    //返回结果决定是否要执行下面的run方法
    @Override
    public boolean shouldFilter() {
        //static/**,/login,/register不需要做登录
        //1.获取request对象,获取请求中的url
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
        log.info("请求地址:"+url);

        //2.判断是否包含在: static/**,/login,/register
        if(url.endsWith("/login")||url.endsWith("/register")||url.endsWith("static")){
            return false;
        }
        return true;

    }


    //核心业务方法:登录检查,如果请求头中有token,则登录成功
    @SneakyThrows
    @Override
    public Object run() {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        //相应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //2.获取请求头中的token
        String token = request.getHeader("token");
        //3.根据是否存在token,判断登录是否成功
        if (!StringUtils.isEmpty(token)){
            try {
            //3.1返回登录检查失败的错误信息:{success:false,msg:"noLogin"}
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("msg","noLogin");
            String jsonString = JSONObject.toJSONString(map);
            PrintWriter writer = response.getWriter();

                writer.write(jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //3.2阻止filter继续往后执行
             RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
